/**
 * Copyright (c) 2020-2024, huli.com
 * All rights reserved.
 */
package com.xiaohujr.xuexue.leetcode;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * @author Xue Xue (xuexue1@huli.com)
 * @version 1.0
 * @since 2020/9/1
 */
public class LruLinkedMap {
    private LinkedHashMap<Integer, Integer> cache;
    private int capacity;

    public LruLinkedMap(int capacity) {
        this.cache = new LinkedHashMap<>(capacity);
        this.capacity = capacity;
    }

    public Integer get(int key) {
        Integer value = this.cache.get(cache);
        if (value == null) {
            return value;
        }
        cache.remove(key);
        cache.put(key, value);
        return value;
    }

    public void set(int key, int value) {
        if (this.cache.containsKey(key)) {
            this.cache.remove(key);

        } else if (this.cache.size() == capacity) {
            Set<Integer> keyset = this.cache.keySet();
            Iterator<Integer> iterator = keyset.iterator();
            this.cache.remove(iterator.next());
        }
        this.cache.put(key, value);
    }

}
